import { genUUID } from './util'
import { initXhr } from './xhr'
import { initErrorEvent } from './error'
import { initUser, getUserId } from './user'
import { initPerformance } from './performance'
import { Log, useDebug } from './log'

export const config = {}

let axios = null;
let evtQueue = [];

const sman = {
  init(opt) {
    Object.assign(config, opt);
    axios = config.axios;
    if (opt.debug) {
      useDebug();
    }

    initUser(this)
    initXhr(this)
    initErrorEvent(this)
    initPerformance(this)

    // SDK 数据上报接口URL
    this.addErrorUrl = opt.url + '/report/error'
    this.addGatewayUrl = opt.url + '/report/gateway'
    this.addPageViewUrl = opt.url + '/report/pageview'
    this.addUserUrl = opt.url + '/report/user/register'

    // 以下URL的请求不上报，避免死循环
    this.ajaxWhiteUrl = [
      this.addErrorUrl,
      this.addGatewayUrl,
      this.addPageViewUrl,
      this.addUserUrl
    ];

    this.userRegister();
  },

  /**
   * @desc 是否为上报系统的接口URL
   */
  isWhiteUrl(url) {
    return Boolean(this.ajaxWhiteUrl.find((it) => url.indexOf(it) === 0))
  },

  // 获取公共参数
  getCommonParams() {
    return {
      app_key: config.app_key,
      event_id: genUUID(),
      user_id: getUserId(),
      platform: 'javascript',
      time: Date.now(),
      request: {
        url: window.location.href,
        'User-Agent': window.navigator.userAgent,
      },
    }
  },

  userRegister() {
    const payload = this.getCommonParams();
    console.log(payload);
    axios({
      url: this.addUserUrl,
      method: 'POST',
      data: payload,
    }).catch((e) => {
      Log.log(`report error: ${e}`)
    })
  },

  /**
   * @description JS异常|资源加载异常
   * @param {*} exception
   */
  sendErrorEevent(exception) {
    const payload = this.getCommonParams()
    payload.exception = exception
    axios({
      url: this.addErrorUrl,
      method: 'POST',
      data: payload,
    }).catch((e) => {
      Log.log(`report error: ${e}`)
    })
  },

  /**
   * @description JS异常|资源加载异常
   * @param {*} exception
   */
  sendErrorEevent(exception) {
    const payload = this.getCommonParams()
    payload.exception = exception
    axios({
      url: this.addErrorUrl,
      method: 'POST',
      data: payload
    }).catch((e) => {
      Log.log(`report error: ${e}`)
    })
  },

  // 页面性能
  sendPageView(params) {
    const payload = this.getCommonParams()
    axios({
      url: this.addPageViewUrl,
      method: 'POST',
      data: {
        page_title: document.title,
        ...payload,
        ...params,
      },
    }).catch((e) => {
      Log.log(`report error: ${e}`)
    })
  },

  // 接口请求上报
  sendXhrEvent(data) {
    const payload = this.getCommonParams()
    if (this.isWhiteUrl(data.url)) return

    axios({
      url: this.addGatewayUrl,
      method: 'POST',
      data: {
        ...payload,
        ...data,
      },
    }).catch((e) => {
      Log.log(`report error: ${e}`)
    })
  },
}

export default sman
